package com.reg;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017-05-18.
 */
public class PlusRegular implements IRegular {

    IRegular regular;


    PlusRegular(IRegular reg){
        regular = reg;
    }

    @Override
    public List<String> match(char[] chars) {
        List<String> strings = regular.match(chars);
        if(null == strings)return null;
        ArrayList<String> allStrings = new ArrayList<String>();
        for(int i = 0 ; i < strings.size();i++){
            String baseString = strings.get(i);
            List<String> matchedStrings = match(strings.get(i), Arrays.copyOfRange(chars,baseString.length(),chars.length));
            if(matchedStrings!=null) {
                allStrings.addAll(matchedStrings);
            }
        }
        return allStrings;
    }

    private List<String> match(String baseString,char[] chars){
        ArrayList<String> strings = new ArrayList<String>();
        StringBuffer sb = new StringBuffer(baseString);
        int i = 0;
        for (;i < chars.length ; i ++){
            if(chars[i] != baseString.charAt(i % baseString.length()))break;
            if((i+1)%baseString.length() == 0)
            {
                sb.append(baseString);
                strings.add(sb.toString());
            }
        }
        return strings;
    }
}
